// JavaScript Document
function vote(ans_id,type)
{
	document.getElementById('voteId').value = ans_id;
	makeRequest('vote.php?ans_id=' + ans_id + '&type=' + type);
}

function makeRequest(url)
{	
	if (window.XMLHttpRequest) request = new XMLHttpRequest();
	else if (typeof ActiveXObject != "undefined")	request = new ActiveXObject("Microsoft.XMLHTTP");
	sendRequest(url);
}

function sendRequest(url)
{
	request.onreadystatechange = onResponse;
	request.open("GET",url,true);
	request.send(null);
}

function onResponse()
{
	if(checkReadyState(request))
	{
		var response = request.responseXML.documentElement;
		var note = response.getElementsByTagName('vote_status')[0].firstChild.data;
		var lang = response.getElementsByTagName('lang')[0].firstChild.data;
		if(note == "voted" && lang=='en') alert("Oops...You voted this answer in the past!");
		else if(note == "voted" && lang=='vn') alert("Xin lỗi, bạn đã bầu chọn câu trả lời này rồi!");
		else
		{
			ans_id = response.getElementsByTagName('ans_id')[0].firstChild.data;
			total = response.getElementsByTagName('total')[0].firstChild.data;
			if(lang == 'en') document.getElementById('vote' + ans_id).innerHTML = total + " Votes";
			else document.getElementById('vote' + ans_id).innerHTML = total + " bầu chọn";
		}
	}
}

function checkReadyState(obj)
{
	var voteid = document.getElementById('voteId').value;
	if(obj.readyState == 0){}
	if(obj.readyState == 1){}
	if(obj.readyState == 2){}
	if(obj.readyState == 3){}
	if(obj.readyState == 4)
		if(obj.status == 200)	return true;
		else if(obj.status == 404)	document.getElementById('vote' + voteid).innerHTML = "File not found";
		else document.getElementById('vote' + voteid).innerHTML = "there was a problem retrieving the XML";
}
